<?php

namespace App\Http\Requests\Admin\User\Permission;

use App\Models\Permission;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;

class UpdateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }


    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $permission = Request::route('permission');

        return [
            //
            'name' => [
                'required',
                function ($attribute, $value, $fail) use ($permission) {
                    if ($permission->name == $value) {
                        return true;
                    }
                    $where = [];
                    $where['name'] = $value;
                    $count = Permission::where($where)->count('id');
                    if ($count) {
                        $fail(":attribute已存在");
                    }
                    if (!preg_match('/[a-zA-Z0-9_]{1,50}$/', $value)) {
                        $fail(":attribute只能是字母数字_且不能多于50个字符");
                    }
                },
                'bail'
            ],
            'display_name' => [
                'required',
                'bail'
            ],
            'description' => [
                function ($attribute, $value, $fail) {
                    if (!preg_match(' /^[a-zA-Z][\w]{1,10}$|^([\x{4e0}-\x{9fa5}]|[\x{4e00}-\x{9fa5}a-z-A-Z\d_]){0,100}$/u', $value)) {
                        $fail(":attribute长度不能大于100字");
                    }
                },
                'bail'
            ],
            'pid' => [
                'required',
                function ($attribute, $value, $fail) use ($permission) {
                    if ($permission->id == $value) {
                        $fail(':attribute不能是自己');
                    }
                    $where = [];
                    $where['id'] = $value;
                    if ($value != 0) {
                        $count = Permission::where($where)->count('id');
                        if (!$count) {
                            $fail(":attribute不存在");
                        }
                    }
                },
                'bail'
            ]
        ];
    }

    public function attributes()
    {
        return [
            'name' => '权限标识',
            'display_name' => '名称',
            'description' => '描述',
            'pid' => '父级'
        ];
    }
}
